package com.weasel.weixin.servlet;

import com.weasel.helper.DocumentConverter;
import com.weasel.weixin.commons.exception.AesException;
import com.weasel.weixin.commons.helper.WeixinEntryptHelper;
import com.weasel.weixin.commons.helper.WeixinMessageDuplicateChecker;
import com.weasel.weixin.commons.message.bean.AbstractWeiXinPostCommonXmlAnswerMessage;
import com.weasel.weixin.commons.message.bean.WeixinPostCommonXmlMessage;
import com.weasel.weixin.commons.message.builder.WeixinPostCommonXmlAnswerMessageBuilders;
import com.weasel.weixin.mp.builder.MpConfigBuilder;
import com.weasel.weixin.mp.config.MpConfig;
import org.apache.commons.lang.StringUtils;
import org.xml.sax.SAXException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;

/**
 * Created by Dylan on 2015/9/28.
 */
public class WeixinPostCommonXmlMessageServlet extends HttpServlet {


    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        response.setContentType("text/html;charset=utf-8");
        response.setStatus(HttpServletResponse.SC_OK);

        String timestamp = request.getParameter("timestamp");
        String nonce = request.getParameter("nonce");
        String signature = request.getParameter("signature");
        String encrypyType = request.getParameter("encrypt_type");
        String msgSignature = request.getParameter("msg_signature");

        WeixinPostCommonXmlMessage message = null;

        MpConfig config = MpConfigBuilder.fromXML("classpath:weixin-config.xml");
        if(StringUtils.equals(encrypyType,"aes")){
            try {
                message = WeixinPostCommonXmlMessage.fromWeixinPostEncryptedInputSteam(config, request.getInputStream(), timestamp, nonce);
            } catch (ParserConfigurationException|SAXException|AesException e) {
                e.printStackTrace();
            }
        }else {
            message = WeixinPostCommonXmlMessage.fromWeixinPostInputSteam(request.getInputStream());
        }

        if(WeixinMessageDuplicateChecker.duplicate(message.getMsgId())){   //如果是重复的消息，直接返回success，不作重复处理
            response.getWriter().write("success");
        }

        AbstractWeiXinPostCommonXmlAnswerMessage answerMessage = WeixinPostCommonXmlAnswerMessageBuilders.answerImage()
                                                                                                         .from(message.getToUserName())
                                                                                                         .to(message.getFromUserName())
                                                                                                         .time(message.getCreateTime())
                                                                                                         .image().mediaId("2aLe038sgCjfr5NNeZF-fax0o18mJZupFdUsYTVVaW4")
                                                                                                                 .end()
                                                                                                         .build();

        if(StringUtils.equals(encrypyType, "aes")){
            try {
                response.getWriter().write(WeixinEntryptHelper.encryptMsg(config, DocumentConverter.toXML(answerMessage),timestamp,nonce));
            } catch (AesException e) {
                e.printStackTrace();
            }
        }else {
            response.getWriter().write(DocumentConverter.toXML(answerMessage));
        }
    }
}
